home *** CD-ROM | disk | FTP | other *** search
- #include <stdio.h>
- enum round_type {ROUND_UP, TRUNCATE, /** other types **/};
-
- void round_double(double value,
- enum round_type round_type, int position,
- char output[])
- {
- double out_value;
- static double round_offset[] =
- {.5, .05, .005, .0005 /* ... */ };
- static char format[][10] =
- {"%.0lf", "%.1lf", "%.2lf", "%.3lf"/* ... */};
- switch(round_type)
- {
- case ROUND_UP:
- /* No change, since printf does rounding */
- out_value = value;
- break;
- case TRUNCATE:
- out_value = value - round_offset[position];
- break;
- /** Any other types of alternatives */
- }
- sprintf(output, format[position], out_value);
- return;
- }
-
- void main()
- {
- double d = 341.456;
- char out[50];
- round_double(d, ROUND_UP, 0, out);
- printf("Output for 0 up %s\n",out);
- round_double(d, ROUND_UP, 1, out);
- printf("Output for 1 up %s\n",out);
- round_double(d, ROUND_UP, 2, out);
- printf("Output for 2 up %s\n",out);
- round_double(d, TRUNCATE, 0, out);
- printf("Output for 0 truncate %s\n",out);
- round_double(d, TRUNCATE, 1, out);
- printf("Output for 1 truncate %s\n",out);
- round_double(d, TRUNCATE, 2, out);
-
- printf("Output for 2 truncate %s\n",out);
- }
-